package com.abso.mp3tunes.locker.ui.actions;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import com.abso.mp3tunes.locker.core.LockerServiceException;
import com.abso.mp3tunes.locker.core.data.AccountData;
import com.abso.mp3tunes.locker.core.data.LoginData;
import com.abso.mp3tunes.locker.core.services.AuthenticationService;
import com.abso.mp3tunes.locker.ui.LockerPlugin;
import com.abso.mp3tunes.locker.ui.dialogs.AccountDataDialog;

/**
 * Action able to open a dialog which shows the current account data.
 */
public class ShowAccountDataAction extends Action {

	/** Constructs a new action. */
	public ShowAccountDataAction() {
		super("Account Information", PlatformUI.getWorkbench()
				.getSharedImages().getImageDescriptor(
						ISharedImages.IMG_OBJS_INFO_TSK));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#run()
	 */
	public void run() {
		Shell shell = LockerPlugin.getActiveWorkbenchShell();
		Display display = shell.getDisplay();

		/* retrieves the existing playlists */
		final List accountDataList = new ArrayList(1);
		BusyIndicator.showWhile(display, new Runnable() {
			public void run() {
				try {
					LoginData loginData = LockerPlugin.getDefault()
							.getLoginData();
					AuthenticationService authService = LockerPlugin
							.getDefault().getAuthenticationService();
					AccountData accountData = authService
							.getAccountData(loginData);
					accountDataList.add(accountData);
				} catch (LockerServiceException e) {

					/* adds the exception to the list */
					accountDataList.add(e);
				}
			}
		});

		/* checks if the retrieval has thrown an error */
		if (!accountDataList.isEmpty()
				&& (accountDataList.get(0) instanceof LockerServiceException)) {
			ErrorDialog.openError(shell, "Error",
					"Unable to show Locker account data", new Status(
							IStatus.ERROR, LockerPlugin.PLUGIN_ID, 0,
							"Unable to log into the Locker",
							(LockerServiceException) accountDataList.get(0)));
			return;
		}

		/* opens the account data dialog */
		new AccountDataDialog((AccountData) accountDataList.get(0), shell)
				.open();
	}

}
